import { ref, nextTick, onMounted } from 'vue'
import { ElMessageBox,ElLoading } from 'element-plus'

export default {
  setup() {
	const showList = ref(true)
	const loadingInstance1 = ElLoading.service({ fullscreen:true,text:'请稍候，查验中...' })
    const tableData = ref([])
	let map = null
	let adress = ""
	let lng = 0
	let lat = 0
	function loadUrlParams(){
		var url = decodeURIComponent(location.search); //获取url中"?"符后的字串
		var theRequest = new Object();
		if (url.indexOf("?") != -1) {
			var str = url.substring(1);
			var strs = str.split("&");
			for(var i = 0; i < strs.length; i ++) {
				theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	}
	function getCodeData(){
		//创建地图
		var paramObj = loadUrlParams();
		console.log(paramObj)
		var tmpUrl = 'http://47.94.221.52:15157/code/verify?id=';
		//tmpUrl = "http://localhost:8080/code/verify?id="
		axios.get(tmpUrl+paramObj.id+"&sign="+paramObj.sign+"&address="+adress+"&lng="+lng+"&lat="+lat, {}).then(function(response) {
			if(response.data.success){
				tableData.value = response.data.data.data
				drawMapLine(response.data.data.line)
				for(var i=0;i<tableData.value.length;i++){
					if(tableData.value[i].type==1){
						tableData.value[i].type="查验成功！"
					}else{
						tableData.value[i].type="查验失败"
					}
					const date = new Date(tableData.value[i].time);
					const formattedDate = date.toLocaleString();
					tableData.value[i].time=formattedDate
					if(map!=null){
						//设置地图点
						var point = new BMapGL.Point(tableData.value[i].pointLat, tableData.value[i].pointLng);
						var mk = new BMapGL.Marker(point);
						map.addOverlay(mk);
					}
				}
				failMessage('验证成功，是正品！')
			}else{
				failMessage('不是正品！')
				console.log(response.data.err);
			}
		}).catch(function (error) {
			console.log(error);
			failMessage('不是正品！')
		});
	}
	//底图画路线轨迹
	function drawMapLine(rline){
		console.log(rline)
		if(map!=null){
			var lineLayer = new BMapGL.LineLayer({
				style: {
					// borderMask: false,
					borderColor: '#ff0000',
					borderWeight: 1,
					strokeWeight: 2,
					strokeColor: '#ff0000'
				}
			});
			lineLayer.setData({
				"type": "FeatureCollection",
				"features": [{
				"type": "Feature",
				"properties": {
					"name": "demo1"
				},
				"geometry": {
					"type": "LineString",
					"coordinates": rline
				}
				}]
			});
			map.addNormalLayer(lineLayer);
		}
	}
	function failMessage(msg){
		loadingInstance1.close()
		ElMessageBox.alert(msg, '消息', {
			confirmButtonText: '确定',
			callback: (action) => {
			  
			},
		  })
	}
	onMounted(() => {
		nextTick(() => {
			createBdMap()
		})
	})
	function createBdMap(){
		map = new window.BMapGL.Map('baidu_map',{
			enableRotate: false,
			enableTilt: false
		});
		var zoomCtrl = new BMapGL.ZoomControl();  // 添加缩放控件
		map.addControl(zoomCtrl);
		var geolocation = new window.BMapGL.Geolocation();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
				var point = new window.BMapGL.Point(r.point.lng, r.point.lat);
				map.centerAndZoom(point, 11);
				console.log("坐标：", r.point.lng, r.point.lat);
				lng = r.point.lng
				lat = r.point.lat
				console.log("坐标：", lng, lat);
				var geoc = new BMapGL.Geocoder();
				geoc.getLocation(r.point, function(rs){
					var addComp = rs.addressComponents;
					adress = addComp.province + "," + addComp.city + "," + addComp.district + "," + addComp.street + "," + addComp.streetNumber
					console.log("详细地址：", addComp, adress);
					getCodeData();
				})
            }else {
				//没有获得地址
                console.log('失败：', this.getStatus());
				setCityCenter();
            }        
        });
	}
	//设置城市中心为地图中心，
	function setCityCenter(){
		var localcity = new window.BMapGL.LocalCity();
		localcity.get(e => {
			console.log("城市中心：", e.center);
			var point = new window.BMapGL.Point(e.center.lng, e.center.lat);
			map.centerAndZoom(point, 11);
			getCodeData();
		});
	}
	//打开地图，并显示中心点，和路径
	function handleBdMap(address, pointLng, pointLat){
		showList.value = false
		if(map!=null){
			//设置中心点
			console.log("当前坐标：", pointLng, pointLat)
			var point = new window.BMapGL.Point(pointLng, pointLat);
			map.centerAndZoom(point, 11);
		}
	}
	function handleMapToList(){
		console.log("返回列表")
		showList.value = true
	}
	return {
		loadingInstance1,showList,map,tableData,loadUrlParams,getCodeData,failMessage,createBdMap,setCityCenter,handleBdMap,handleMapToList
	}
  }
}